const { sequelize } = require('../models')
const { 
  User, Role, Permission, UserRole, RolePermission,
  Product, ProductCategory, Customer, Order, OrderItem, 
  Inventory, TableConfig, TableColumn, TableTheme, TableAction 
} = require('../models')
const bcrypt = require('bcryptjs')

const initData = async () => {
  try {
    console.log('开始初始化数据库数据...')
    
    // 强制同步数据库
    await sequelize.sync({ force: true })
    console.log('✅ 数据库表结构已重置')

    // 1. 创建权限
    const permissions = await Permission.bulkCreate([
      // 产品管理权限
      { name: '产品查看', code: 'product:read', resource: 'product', action: 'read' },
      { name: '产品创建', code: 'product:create', resource: 'product', action: 'create' },
      { name: '产品编辑', code: 'product:update', resource: 'product', action: 'update' },
      { name: '产品删除', code: 'product:delete', resource: 'product', action: 'delete' },
      
      // 客户管理权限
      { name: '客户查看', code: 'customer:read', resource: 'customer', action: 'read' },
      { name: '客户创建', code: 'customer:create', resource: 'customer', action: 'create' },
      { name: '客户编辑', code: 'customer:update', resource: 'customer', action: 'update' },
      { name: '客户删除', code: 'customer:delete', resource: 'customer', action: 'delete' },
      
      // 订单管理权限
      { name: '订单查看', code: 'order:read', resource: 'order', action: 'read' },
      { name: '订单创建', code: 'order:create', resource: 'order', action: 'create' },
      { name: '订单编辑', code: 'order:update', resource: 'order', action: 'update' },
      { name: '订单删除', code: 'order:delete', resource: 'order', action: 'delete' },
      
      // 库存管理权限
      { name: '库存查看', code: 'inventory:read', resource: 'inventory', action: 'read' },
      { name: '库存调整', code: 'inventory:update', resource: 'inventory', action: 'update' },
      
      // 用户管理权限
      { name: '用户查看', code: 'user:read', resource: 'user', action: 'read' },
      { name: '用户创建', code: 'user:create', resource: 'user', action: 'create' },
      { name: '用户编辑', code: 'user:update', resource: 'user', action: 'update' },
      { name: '用户删除', code: 'user:delete', resource: 'user', action: 'delete' },
      
      // 角色管理权限
      { name: '角色查看', code: 'role:read', resource: 'role', action: 'read' },
      { name: '角色创建', code: 'role:create', resource: 'role', action: 'create' },
      { name: '角色编辑', code: 'role:update', resource: 'role', action: 'update' },
      { name: '角色删除', code: 'role:delete', resource: 'role', action: 'delete' },
      
      // 系统设置权限
      { name: '系统设置', code: 'system:manage', resource: 'system', action: 'manage' },
      
      // 聊天权限
      { name: '聊天查看', code: 'chat:read', resource: 'chat', action: 'read' },
      { name: '聊天写入', code: 'chat:write', resource: 'chat', action: 'write' },
      { name: '聊天删除', code: 'chat:delete', resource: 'chat', action: 'delete' },
    ])
    console.log('✅ 权限数据已创建')

    // 2. 创建角色
    const roles = await Role.bulkCreate([
      { name: '超级管理员', code: 'super_admin', description: '拥有系统所有权限' },
      { name: '管理员', code: 'admin', description: '拥有大部分管理权限' },
      { name: '销售员', code: 'sales', description: '负责客户和订单管理' },
      { name: '仓库管理员', code: 'warehouse', description: '负责库存管理' },
    ])
    console.log('✅ 角色数据已创建')

    // 3. 分配角色权限
    const superAdminRole = roles[0]
    const adminRole = roles[1]
    const salesRole = roles[2]
    const warehouseRole = roles[3]

    // 超级管理员拥有所有权限
    await superAdminRole.setPermissions(permissions)
    
    // 管理员权限（除了系统管理）
    const adminPermissions = permissions.filter(p => !p.code.includes('system') && !p.code.includes('role'))
    await adminRole.setPermissions(adminPermissions)
    
    // 销售员权限
    const salesPermissions = permissions.filter(p => 
      p.resource === 'customer' || p.resource === 'order' || 
      (p.resource === 'product' && p.action === 'read') ||
      (p.resource === 'chat') // 销售员也可以使用聊天功能
    )
    await salesRole.setPermissions(salesPermissions)
    
    // 仓库管理员权限
    const warehousePermissions = permissions.filter(p => 
      p.resource === 'inventory' || 
      (p.resource === 'product' && p.action === 'read') ||
      (p.resource === 'chat') // 仓库管理员也可以使用聊天功能
    )
    await warehouseRole.setPermissions(warehousePermissions)

    console.log('✅ 角色权限分配完成')

    // 4. 创建用户
    const users = await User.bulkCreate([
      {
        username: 'xos999999',
        password: await bcrypt.hash('xos999999', 10),
        email: 'admin@xsynergy.com',
        real_name: '超级管理员',
        phone: '13800138000',
        status: 'active'
      },
      {
        username: 'manager',
        password: await bcrypt.hash('123456', 10),
        email: 'manager@xsynergy.com',
        real_name: '普通管理员',
        phone: '13800138001',
        status: 'active'
      },
      {
        username: 'sales',
        password: await bcrypt.hash('123456', 10),
        email: 'sales@xsynergy.com',
        real_name: '销售员',
        phone: '13800138002',
        status: 'active'
      },
      {
        username: 'warehouse',
        password: await bcrypt.hash('123456', 10),
        email: 'warehouse@xsynergy.com',
        real_name: '仓库管理员',
        phone: '13800138003',
        status: 'active'
      }
    ])
    console.log('✅ 用户数据已创建')

    // 5. 分配用户角色
    await users[0].setRoles([superAdminRole])
    await users[1].setRoles([adminRole])
    await users[2].setRoles([salesRole])
    await users[3].setRoles([warehouseRole])
    console.log('✅ 用户角色分配完成')

    // 6. 创建产品分类
    const categories = await ProductCategory.bulkCreate([
      { name: '电子产品', code: 'electronics', description: '各类电子设备' },
      { name: '办公用品', code: 'office', description: '办公室常用物品' },
      { name: '服装鞋帽', code: 'clothing', description: '服装类商品' },
      { name: '食品饮料', code: 'food', description: '食品和饮料' },
      { name: '家居用品', code: 'home', description: '家庭日用品' }
    ])
    console.log('✅ 产品分类已创建')

    // 7. 创建产品
    const products = await Product.bulkCreate([
      {
        name: 'iPhone 15 Pro',
        sku: 'IP15P001',
        description: '苹果最新旗舰手机',
        category_id: categories[0].id,
        price: 8999.00,
        cost: 6500.00,
        unit: '台',
        status: 'active',
        created_by: users[0].id
      },
      {
        name: 'MacBook Pro 16',
        sku: 'MBP16001',
        description: '苹果笔记本电脑',
        category_id: categories[0].id,
        price: 19999.00,
        cost: 15000.00,
        unit: '台',
        status: 'active',
        created_by: users[0].id
      },
      {
        name: '办公椅',
        sku: 'OFC001',
        description: '人体工学办公椅',
        category_id: categories[1].id,
        price: 899.00,
        cost: 500.00,
        unit: '把',
        status: 'active',
        created_by: users[0].id
      },
      {
        name: '商务衬衫',
        sku: 'SHT001',
        description: '男士商务长袖衬衫',
        category_id: categories[2].id,
        price: 299.00,
        cost: 150.00,
        unit: '件',
        status: 'active',
        created_by: users[0].id
      },
      {
        name: '咖啡豆',
        sku: 'CFB001',
        description: '蓝山咖啡豆 500g',
        category_id: categories[3].id,
        price: 168.00,
        cost: 100.00,
        unit: '包',
        status: 'active',
        created_by: users[0].id
      }
    ])
    console.log('✅ 产品数据已创建')

    // 8. 创建库存记录
    const inventories = []
    for (const product of products) {
      inventories.push({
        product_id: product.id,
        quantity: Math.floor(Math.random() * 1000) + 100,
        reserved_quantity: Math.floor(Math.random() * 50),
        min_stock: 50,
        max_stock: 1000,
        warehouse_location: `A-${Math.floor(Math.random() * 10) + 1}-${Math.floor(Math.random() * 20) + 1}`
      })
    }
    await Inventory.bulkCreate(inventories)
    console.log('✅ 库存数据已创建')

    // 9. 创建客户
    const customers = await Customer.bulkCreate([
      {
        name: '北京科技有限公司',
        code: 'BJ001',
        type: 'enterprise',
        contact_person: '张经理',
        phone: '010-88888888',
        email: 'zhang@bjtech.com',
        address: '北京市海淀区中关村大街1号',
        credit_limit: 100000.00,
        status: 1
      },
      {
        name: '上海贸易公司',
        code: 'SH001',
        type: 'enterprise',
        contact_person: '李总',
        phone: '021-66666666',
        email: 'li@shtrade.com',
        address: '上海市浦东新区陆家嘴金融中心',
        credit_limit: 200000.00,
        status: 1
      },
      {
        name: '王小明',
        code: 'IND001',
        type: 'individual',
        contact_person: '王小明',
        phone: '13912345678',
        email: 'wangxm@email.com',
        address: '江苏省南京市鼓楼区',
        credit_limit: 10000.00,
        status: 1
      }
    ])
    console.log('✅ 客户数据已创建')

    // 10. 创建订单
    const orders = []
    for (let i = 0; i < 10; i++) {
      const customer = customers[i % customers.length]
      const orderProducts = products.slice(0, Math.floor(Math.random() * 3) + 1)
      
      let subtotal = 0
      const orderItems = []
      
      for (const product of orderProducts) {
        const quantity = Math.floor(Math.random() * 5) + 1
        const itemSubtotal = quantity * product.price
        subtotal += itemSubtotal
        
        orderItems.push({
          product_id: product.id,
          product_name: product.name, // 添加产品名称快照
          product_sku: product.sku,   // 添加产品SKU快照
          quantity,
          unit_price: product.price,
          discount_rate: 0,
          discount_amount: 0,
          line_total: itemSubtotal,   // 添加行总金额
          subtotal: itemSubtotal      // 保持原有字段兼容性
        })
      }
      
      const order = await Order.create({
        order_no: `ORD${new Date().getFullYear()}${String(Date.now()).slice(-6)}${String(i).padStart(3, '0')}`,
        customer_id: customer.id,
        order_date: new Date(),
        subtotal,
        discount_amount: 0,
        shipping_fee: subtotal > 1000 ? 0 : 50,
        total_amount: subtotal + (subtotal > 1000 ? 0 : 50),
        status: ['pending', 'confirmed', 'shipped', 'delivered'][Math.floor(Math.random() * 4)],
        payment_status: 'unpaid',
        currency: 'CNY',
        created_by: users[Math.floor(Math.random() * users.length)].id
      })
      
      // 创建订单项
      for (const item of orderItems) {
        await OrderItem.create({
          ...item,
          order_id: order.id
        })
      }
      
      orders.push(order)
    }
    console.log('✅ 订单数据已创建')

    // 11. 创建动态表格配置 - 为每个页面创建表格配置
    const tableConfigs = await TableConfig.bulkCreate([
      {
        table_id: 'product_table',
        name: '产品管理表格',
        table_name: '产品列表',
        description: '产品管理表格配置',
        default_page_size: 10,
        export_enabled: true,
        status: 'active',
        created_by: users[0].id
      },
      {
        table_id: 'customer_table',
        name: '客户管理表格',
        table_name: '客户列表',
        description: '客户管理表格配置',
        default_page_size: 10,
        export_enabled: true,
        status: 'active',
        created_by: users[0].id
      },
      {
        table_id: 'order_table',
        name: '订单管理表格',
        table_name: '订单列表',
        description: '订单管理表格配置',
        default_page_size: 10,
        export_enabled: true,
        status: 'active',
        created_by: users[0].id
      },
      {
        table_id: 'inventory_table',
        name: '库存管理表格',
        table_name: '库存列表',
        description: '库存管理表格配置',
        default_page_size: 10,
        export_enabled: true,
        status: 'active',
        created_by: users[0].id
      },
      {
        table_id: 'user_table',
        name: '用户管理表格',
        table_name: '用户列表',
        description: '用户管理表格配置',
        default_page_size: 10,
        export_enabled: true,
        status: 'active',
        created_by: users[0].id
      },
      {
        table_id: 'role_table',
        name: '角色管理表格',
        table_name: '角色列表',
        description: '角色管理表格配置',
        default_page_size: 10,
        export_enabled: true,
        status: 'active',
        created_by: users[0].id
      },
      {
        table_id: 'permission_table',
        name: '权限管理表格',
        table_name: '权限列表',
        description: '权限管理表格配置',
        default_page_size: 10,
        export_enabled: true,
        status: 'active',
        created_by: users[0].id
      }
    ])
    console.log('✅ 表格配置已创建')

    // 12. 为每个表格创建列配置
    
    // 产品表格列配置
    const productTableConfig = tableConfigs.find(t => t.table_id === 'product_table')
    await TableColumn.bulkCreate([
      {
        table_config_id: productTableConfig.id,
        key: 'id',
        title: 'ID',
        width: 80,
        sortable: true,
        filterable: false,
        visible: true,
        sort_order: 1,
        value_type: 'number',
        status: 'active'
      },
      {
        table_config_id: productTableConfig.id,
        key: 'name',
        title: '产品名称',
        width: 200,
        sortable: true,
        filterable: true,
        visible: true,
        sort_order: 2,
        value_type: 'text',
        status: 'active'
      },
      {
        table_config_id: productTableConfig.id,
        key: 'sku',
        title: 'SKU',
        width: 150,
        sortable: true,
        filterable: true,
        visible: true,
        sort_order: 3,
        value_type: 'text',
        status: 'active'
      },
      {
        table_config_id: productTableConfig.id,
        key: 'price',
        title: '价格',
        width: 120,
        sortable: true,
        filterable: false,
        visible: true,
        sort_order: 4,
        value_type: 'currency',
        status: 'active'
      },
      {
        table_config_id: productTableConfig.id,
        key: 'category_name',
        title: '分类',
        width: 120,
        sortable: true,
        filterable: true,
        visible: true,
        sort_order: 5,
        value_type: 'text',
        status: 'active'
      },
      {
        table_config_id: productTableConfig.id,
        key: 'status',
        title: '状态',
        width: 100,
        sortable: true,
        filterable: true,
        visible: true,
        sort_order: 6,
        value_type: 'tag',
        status: 'active'
      }
    ])
    console.log('✅ 产品表格列配置已创建')

    // 客户表格列配置
    const customerTableConfig = tableConfigs.find(t => t.table_id === 'customer_table')
    await TableColumn.bulkCreate([
      { table_config_id: customerTableConfig.id, key: 'id', title: 'ID', width: 80, sortable: true, filterable: false, visible: true, sort_order: 1, value_type: 'number', status: 'active' },
      { table_config_id: customerTableConfig.id, key: 'name', title: '客户名称', width: 200, sortable: true, filterable: true, visible: true, sort_order: 2, value_type: 'text', status: 'active' },
      { table_config_id: customerTableConfig.id, key: 'code', title: '客户编码', width: 120, sortable: true, filterable: true, visible: true, sort_order: 3, value_type: 'text', status: 'active' },
      { table_config_id: customerTableConfig.id, key: 'type', title: '客户类型', width: 100, sortable: true, filterable: true, visible: true, sort_order: 4, value_type: 'tag', status: 'active' },
      { table_config_id: customerTableConfig.id, key: 'contact_person', title: '联系人', width: 120, sortable: true, filterable: true, visible: true, sort_order: 5, value_type: 'text', status: 'active' },
      { table_config_id: customerTableConfig.id, key: 'phone', title: '联系电话', width: 140, sortable: false, filterable: true, visible: true, sort_order: 6, value_type: 'text', status: 'active' },
      { table_config_id: customerTableConfig.id, key: 'status', title: '状态', width: 100, sortable: true, filterable: true, visible: true, sort_order: 7, value_type: 'tag', status: 'active' }
    ])
    console.log('✅ 客户表格列配置已创建')

    // 订单表格列配置
    const orderTableConfig = tableConfigs.find(t => t.table_id === 'order_table')
    await TableColumn.bulkCreate([
      { table_config_id: orderTableConfig.id, key: 'id', title: 'ID', width: 80, sortable: true, filterable: false, visible: true, sort_order: 1, value_type: 'number', status: 'active' },
      { table_config_id: orderTableConfig.id, key: 'order_no', title: '订单编号', width: 150, sortable: true, filterable: true, visible: true, sort_order: 2, value_type: 'text', status: 'active' },
      { table_config_id: orderTableConfig.id, key: 'customer_name', title: '客户名称', width: 150, sortable: true, filterable: true, visible: true, sort_order: 3, value_type: 'text', status: 'active' },
      { table_config_id: orderTableConfig.id, key: 'total_amount', title: '订单金额', width: 120, sortable: true, filterable: false, visible: true, sort_order: 4, value_type: 'currency', status: 'active' },
      { table_config_id: orderTableConfig.id, key: 'status', title: '订单状态', width: 100, sortable: true, filterable: true, visible: true, sort_order: 5, value_type: 'tag', status: 'active' },
      { table_config_id: orderTableConfig.id, key: 'created_at', title: '创建时间', width: 160, sortable: true, filterable: false, visible: true, sort_order: 6, value_type: 'datetime', status: 'active' }
    ])
    console.log('✅ 订单表格列配置已创建')

    // 库存、用户、角色、权限表格列配置
    const inventoryTableConfig = tableConfigs.find(t => t.table_id === 'inventory_table')
    const userTableConfig = tableConfigs.find(t => t.table_id === 'user_table')
    const roleTableConfig = tableConfigs.find(t => t.table_id === 'role_table')
    const permissionTableConfig = tableConfigs.find(t => t.table_id === 'permission_table')
    
    // 库存表格列
    await TableColumn.bulkCreate([
      { table_config_id: inventoryTableConfig.id, key: 'id', title: 'ID', width: 80, sort_order: 1, value_type: 'number', status: 'active' },
      { table_config_id: inventoryTableConfig.id, key: 'product_name', title: '产品名称', width: 200, sort_order: 2, value_type: 'text', status: 'active' },
      { table_config_id: inventoryTableConfig.id, key: 'quantity', title: '现有库存', width: 100, sort_order: 3, value_type: 'number', status: 'active' },
      { table_config_id: inventoryTableConfig.id, key: 'reserved_quantity', title: '预留库存', width: 100, sort_order: 4, value_type: 'number', status: 'active' },
      { table_config_id: inventoryTableConfig.id, key: 'min_stock', title: '最小库存', width: 100, sort_order: 5, value_type: 'number', status: 'active' },
      { table_config_id: inventoryTableConfig.id, key: 'warehouse_location', title: '仓库位置', width: 120, sort_order: 6, value_type: 'text', status: 'active' }
    ])
    
    // 用户表格列
    await TableColumn.bulkCreate([
      { table_config_id: userTableConfig.id, key: 'id', title: 'ID', width: 80, sort_order: 1, value_type: 'number', status: 'active' },
      { table_config_id: userTableConfig.id, key: 'username', title: '用户名', width: 120, sort_order: 2, value_type: 'text', status: 'active' },
      { table_config_id: userTableConfig.id, key: 'real_name', title: '真实姓名', width: 120, sort_order: 3, value_type: 'text', status: 'active' },
      { table_config_id: userTableConfig.id, key: 'email', title: '邮箱', width: 180, sort_order: 4, value_type: 'text', status: 'active' },
      { table_config_id: userTableConfig.id, key: 'phone', title: '手机号', width: 140, sort_order: 5, value_type: 'text', status: 'active' },
      { table_config_id: userTableConfig.id, key: 'status', title: '状态', width: 100, sort_order: 6, value_type: 'tag', status: 'active' }
    ])
    
    // 角色表格列
    await TableColumn.bulkCreate([
      { table_config_id: roleTableConfig.id, key: 'id', title: 'ID', width: 80, sort_order: 1, value_type: 'number', status: 'active' },
      { table_config_id: roleTableConfig.id, key: 'name', title: '角色名称', width: 150, sort_order: 2, value_type: 'text', status: 'active' },
      { table_config_id: roleTableConfig.id, key: 'code', title: '角色编码', width: 120, sort_order: 3, value_type: 'text', status: 'active' },
      { table_config_id: roleTableConfig.id, key: 'description', title: '描述', width: 200, sort_order: 4, value_type: 'text', status: 'active' },
      { table_config_id: roleTableConfig.id, key: 'created_at', title: '创建时间', width: 160, sort_order: 5, value_type: 'datetime', status: 'active' }
    ])
    
    // 权限表格列
    await TableColumn.bulkCreate([
      { table_config_id: permissionTableConfig.id, key: 'id', title: 'ID', width: 80, sort_order: 1, value_type: 'number', status: 'active' },
      { table_config_id: permissionTableConfig.id, key: 'name', title: '权限名称', width: 150, sort_order: 2, value_type: 'text', status: 'active' },
      { table_config_id: permissionTableConfig.id, key: 'code', title: '权限编码', width: 120, sort_order: 3, value_type: 'text', status: 'active' },
      { table_config_id: permissionTableConfig.id, key: 'resource', title: '资源', width: 100, sort_order: 4, value_type: 'text', status: 'active' },
      { table_config_id: permissionTableConfig.id, key: 'action', title: '操作', width: 100, sort_order: 5, value_type: 'text', status: 'active' }
    ])
    
    console.log('✅ 所有表格列配置已创建')

    // 13. 创建表格主题配置
    await TableTheme.bulkCreate([
      {
        theme_id: 'default',
        name: '默认主题',
        description: '系统默认主题',
        colors: {
          primary: '#1890ff',
          success: '#52c41a',
          warning: '#faad14',
          error: '#f5222d',
          border: '#d9d9d9',
          background: '#ffffff',
          text: '#262626'
        },
        fonts: {
          header: '16px',
          body: '14px',
          small: '12px'
        },
        spacing: {
          padding: '8px',
          margin: '4px'
        },
        is_default: true,
        status: 'active',
        created_by: users[0].id
      },
      {
        theme_id: 'clean',
        name: '简洁主题',
        description: '简洁明亮的表格主题',
        colors: {
          primary: '#52c41a',
          success: '#52c41a',
          warning: '#fa8c16',
          error: '#f5222d',
          border: '#b7eb8f',
          background: '#ffffff',
          text: '#333333'
        },
        fonts: {
          header: '15px',
          body: '13px',
          small: '11px'
        },
        spacing: {
          padding: '6px',
          margin: '3px'
        },
        is_default: false,
        status: 'active',
        created_by: users[0].id
      },
      {
        theme_id: 'dark',
        name: '深色主题',
        description: '深色风格的表格主题',
        colors: {
          primary: '#722ed1',
          success: '#49aa19',
          warning: '#d89614',
          error: '#d32029',
          border: '#434343',
          background: '#001529',
          text: '#ffffff'
        },
        fonts: {
          header: '16px',
          body: '14px',
          small: '12px'
        },
        spacing: {
          padding: '8px',
          margin: '4px'
        },
        is_default: false,
        status: 'active',
        created_by: users[0].id
      }
    ])
    console.log('✅ 表格主题配置已创建')

    // 14. 创建表格操作配置
    await TableAction.bulkCreate([
      {
        action_id: 'view',
        name: '查看',
        description: '查看详情',
        icon: 'EyeOutlined',
        color: '#1890ff',
        permission: 'view',
        confirm_required: false,
        api_endpoint: '/detail',
        http_method: 'GET',
        status: 'active',
        created_by: users[0].id
      },
      {
        action_id: 'edit',
        name: '编辑',
        description: '编辑记录',
        icon: 'EditOutlined',
        color: '#52c41a',
        permission: 'edit',
        confirm_required: false,
        api_endpoint: '/update',
        http_method: 'PUT',
        status: 'active',
        created_by: users[0].id
      },
      {
        action_id: 'delete',
        name: '删除',
        description: '删除记录',
        icon: 'DeleteOutlined',
        color: '#f5222d',
        permission: 'delete',
        confirm_required: true,
        confirm_message: '确定要删除这条记录吗？',
        api_endpoint: '/delete',
        http_method: 'DELETE',
        status: 'active',
        created_by: users[0].id
      },
      {
        action_id: 'create',
        name: '新增',
        description: '新增记录',
        icon: 'PlusOutlined',
        color: '#1890ff',
        permission: 'create',
        confirm_required: false,
        api_endpoint: '/create',
        http_method: 'POST',
        status: 'active',
        created_by: users[0].id
      },
      {
        action_id: 'batch_delete',
        name: '批量删除',
        description: '批量删除选中记录',
        icon: 'DeleteOutlined',
        color: '#f5222d',
        permission: 'delete',
        confirm_required: true,
        confirm_message: '确定要删除选中的记录吗？',
        api_endpoint: '/batch-delete',
        http_method: 'DELETE',
        status: 'active',
        created_by: users[0].id
      },
      {
        action_id: 'export',
        name: '导出',
        description: '导出Excel',
        icon: 'ExportOutlined',
        color: '#52c41a',
        permission: 'export',
        confirm_required: false,
        api_endpoint: '/export',
        http_method: 'GET',
        status: 'active',
        created_by: users[0].id
      },
      {
        action_id: 'refresh',
        name: '刷新',
        description: '刷新数据',
        icon: 'ReloadOutlined',
        color: '#722ed1',
        permission: 'view',
        confirm_required: false,
        api_endpoint: '/list',
        http_method: 'GET',
        status: 'active',
        created_by: users[0].id
      }
    ])
    console.log('✅ 表格操作配置已创建')

    console.log('🎉 数据库数据初始化完成！')
    console.log('\n📋 创建的数据统计:')
    console.log(`- 权限: ${permissions.length} 个`)
    console.log(`- 角色: ${roles.length} 个`)
    console.log(`- 用户: ${users.length} 个`)
    console.log(`- 产品分类: ${categories.length} 个`)
    console.log(`- 产品: ${products.length} 个`)
    console.log(`- 客户: ${customers.length} 个`)
    console.log(`- 订单: ${orders.length} 个`)
    console.log(`- 表格配置: ${tableConfigs.length} 个`)
    console.log('- 表格列配置: 所有页面都已配置完成')
    console.log('- 表格主题: 3 个')
    console.log('- 表格操作: 7 个')
    
    console.log('\n👤 测试账号:')
    console.log('- 超级管理员: xos999999 / xos999999')
    console.log('- 普通管理员: manager / 123456')
    console.log('- 销售员: sales / 123456')
    console.log('- 仓库管理员: warehouse / 123456')

  } catch (error) {
    console.error('❌ 数据初始化失败:', error)
    throw error
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  initData()
    .then(() => {
      console.log('✅ 初始化脚本执行完成')
      process.exit(0)
    })
    .catch((error) => {
      console.error('❌ 初始化脚本执行失败:', error)
      process.exit(1)
    })
}

module.exports = { initData }